import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'
// 导入用户相关API
import { reqUserLogin } from '@/api/user'


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    async login(user_name: string, user_passwd: string, user_email: string) {

      // 获取返回成功的数据：token
      let result = await reqUserLogin({ user_name, user_passwd, user_email });
      console.log("result");

      console.log(result);

      // 假设 result 是接口返回的完整响应数据（即包含 msg/code/success/data 的对象）
      if (result && result.success && result.data?.Authorization) {
        // 从 data.Authorization 提取 Token
        this.token = result.data.Authorization;
        setToken(result.data.Authorization);
        // 使用后端返回的 msg 动态提示
        ElMessage.success(result.msg || '登录成功');
      } else {
        // 根据后端返回的 msg 显示错误（若存在），否则显示默认提示
        const errorMsg = result?.msg || '登录失败，请检查用户名、密码和邮箱';
        ElMessage.error(errorMsg);
      }


    },

    getInfo() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = 'admin'
          this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          this.menuRoutes = staticRoutes
          resolve({ name: this.name, avatar: this.avatar, token: this.token })
        }, 1000)
      })
    },

    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
  },
});
